package org.cmroot.certmaster.dao.impl;

import org.cmroot.certmaster.dao.GenericDaoException;
import org.cmroot.certmaster.dao.X509Dao;
import org.cmroot.certmaster.model.X509;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Copyright (c) 2010 Andrey Domas <andrey.domas at gmail.com>.
 * *
 * This file is part of certmaster.
 * *
 * Certmaster is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * *
 * Certmaster is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 */

@Component
@Qualifier("x509_hibernate")
public class X509DaoHibernateImpl extends GenericDaoHibernateImpl<X509> implements X509Dao {
    @Override
    public List<X509> findByIssuer(X509 issuer) throws GenericDaoException {
        try {
            Query query = getSession().createQuery( "from X509 x where x.issuer "
                                                    + (issuer == null ? "is null" : "= " +issuer.getId()) );
            return (List<X509>) query.list();
        } catch (DataAccessException e) {
            throw new GenericDaoException(e);
        }
    }

    @Override
    public Long countChildern(Long cert_id) throws GenericDaoException {
        try {
            Query query = this.getSession().createQuery("select count(id) from X509 where issuer_id = " + cert_id);
            return (Long) query.uniqueResult();
        } catch (DataAccessException e) {
            throw new GenericDaoException(e);
        }
    }

    @Override
    public List<X509> findCA() throws GenericDaoException {
        try {
            Query query = this.getSession().createQuery("from X509 x where x.CA = true");
            return (List<X509>) query.list();
        } catch (DataAccessException e) {
            throw new GenericDaoException(e);
        }
    }
}
